package com.yuri.news.controller;

import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yuri.news.domain.Pages;
import com.yuri.news.domain.Result;
import com.yuri.news.entity.News;
import com.yuri.news.service.NewsService;

/**
 * 新闻控制器
 * @author Yuri
 *
 */
// 允许跨域访问
@CrossOrigin
// 控制器
@Controller
//以json形式返回
@ResponseBody
@SuppressWarnings("deprecation")
public class NewsController {
	// 日志打印
	private final Logger logger =  LoggerFactory.getLogger(NewsController.class);
	// 依赖注入
	@Autowired
	NewsService newsService;
	
	/**
	 * 添加新闻
	 * @param news
	 * @return
	 */
	@RequestMapping(value = "addNews", method = RequestMethod.POST)
	public Result<News> addNews(News news) {
		logger.info("\n 添加新闻(addNews)开始 news = " + news);
		Result<News> result = new Result<News>();
		try {
			News ns = newsService.saveNews(news);
			if(ns != null) {
				result.setSuccess("添加成功");
			}else {
				result.setError("添加失败！");
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			result.setError("发生异常错误！");
		}
		
		logger.info("\n 添加新闻(addNews)结束 news = " + news);
		return result;
	}
	/**
	 * 修改新闻！
	 * @param news
	 * @return
	 */
	@RequestMapping(value = "modifyNews", method = RequestMethod.PUT)
	public Result<News> modifyJour(News news) {
		// 日志打印
		logger.info("\n 修改新闻(modifyNews)开始 news = " + news);
		Result<News> result = new Result<News>();
		try {
			if(newsService.updapeNews(news)) {
				result.setSuccess("修改成功！");
			}else {
				result.setError("无此条新闻信息！");
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			result.setError("发生异常错误！");
		}
		logger.info("\n 修改新闻(modifyNews)结束 result = " + result);
		return result;
	}
	
	/**
	 * 删除新闻！
	 * @param news
	 * @return
	 */
	@RequestMapping(value = "delNews", method = RequestMethod.DELETE)
	public Result<News> delJour(News news) {
		// 日志打印
		logger.info("\n 删除新闻(delNews)开始 news = " + news);
		Result<News> result = new Result<News>();
		
		try {
			newsService.deleteNews(news);
			result.setSuccess("删除成功！");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			result.setError("发生异常错误！");
		}
		logger.info("\n 删除新闻(delNews)结束 news = " + news);
		return result;
	}
	
	/**
	 * 查看所有新闻
	 * @param page		当前页
	 * @param size		每页大小
	 * @return
	 */
	@RequestMapping(value = "findNewsAll", method = RequestMethod.GET)
	public Result<News> findNewsAll(
			@RequestParam(name = "page",defaultValue="0") Integer page,
			@RequestParam(name = "size", defaultValue="10") Integer size) {
		logger.info("\n 查看所有(findNewsAll)开始  page = " + page + "\t size" + size);
		// 存放返回数据
		Result<News> result = new Result<News>();
		try {
			Page<News> news = null;
			// 分页信息
			Order order 	= new Order(Direction.ASC, "id"); // 根据字段id进行升序排序
			PageRequest pageRequest = PageRequest.of(page, size, new Sort(order));// 分页排序查询
			
			news = newsService.listNews(pageRequest);
			
			if(news !=null && news.getContent() != null && news.getContent().size() > 0) {
				Pages pages = new Pages(page, news.getTotalElements(), size);
				
				result.setData(news.getContent());
				result.setPages(pages);
				result.setSuccess("查询成功！");
			}else {
				result.setError("暂时无新闻！请稍后再试");
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			result.setError("发生异常错误！");
		}
		logger.info("\n 查看所有(findNewsAll)结束  result = " + result);
		return result;
	}
	/**
	 * 根据id查询新闻
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "findNewsById",method = RequestMethod.GET)
	public Result<News> findNewsById(Long id) {
		// 日志打印
		logger.info("\n 根据id查询新闻(findNewsById)开始 id = " + id);
		Result<News> result = new Result<News>();
		
		try {
			List<News> newss = new ArrayList<>();
			News news = newsService.getNewsById(id);
			
			if(news != null) {
				newss.add(news);
				result.setData(newss);
				result.setSuccess("查询成功！");
			}else {
				result.setError("无此新闻信息！");
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			result.setError("发生异常错误！");
		}
		
		logger.info("\n 根据id查询新闻(findNewsById)结束 result = " + result);
		return result;
	}
	
	/**
	 * 根据关键字Key查询新闻
	 * @param key		关键字
	 * @param page		当前页数
	 * @param size		每页数据条数
	 * @return
	 */
	@RequestMapping(value = "findNewsByKey", method = RequestMethod.GET)
	public Result<News> findNewsByKey(
			@RequestParam(name = "key", defaultValue = "") String key,
			@RequestParam(name = "page",defaultValue = "0") Integer page,
			@RequestParam(name = "size", defaultValue= "10") Integer size) {
		logger.info("\n 根据关键字Key查询新闻(findNewsByKey)开始 key = " + key);
		Result<News> result = new Result<News>();
		try {
			// 分页信息
			Order order 	= new Order(Direction.ASC, "id"); // 根据字段id进行升序排序
			PageRequest pageRequest = PageRequest.of(page, size, new Sort(order));// 分页排序查询
			// 存放查询的信息
			Page<News> newss = null;
			
			newss = newsService.listNewsByKey(key, pageRequest);
			
			if(newss != null && newss.getContent() != null && newss.getContent().size() > 0) {
				Pages pages = new Pages(page, newss.getTotalElements(), size);
				
				result.setPages(pages);
				result.setData(newss.getContent());
				result.setSuccess("查询成功！");
			}else {
				result.setError("无此新闻数据");
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			result.setError("发生异常错误！");
		}
		logger.info("\n 根据关键字Key查询新闻(findNewsByKey)结束 result = " + result);
		return result;
	}
	/**
	 * 根据分类id查询新闻信息
	 * @param id		分类id
	 * @param page		当前页
	 * @param size		每页显示数据数
	 * @return 
	 */
	@RequestMapping(value = "findByClassId", method = RequestMethod.GET)
	public Result<News> findByClassId(Long id,
			@RequestParam(value = "page",defaultValue = "0") Integer page,
			@RequestParam(value = "size", defaultValue = "10") Integer size){
		logger.info("\n 根据分类id查询新闻信息（）开始 id = " + id + "\t page = " + page + "\t size = " + size);
		Result<News> result = new Result<>();
		try {
			// 分页信息
			Order order 	= new Order(Direction.ASC, "id"); // 根据字段id进行升序排序
			PageRequest pageRequest = PageRequest.of(page, size, new Sort(order));// 分页排序查询
			Page<News> newss = null;
			
			newss = newsService.listNewsByClassId(id, pageRequest);
			
			if(newss != null && newss.getContent() != null && newss.getContent().size() > 0) {
				Pages pages = new Pages(page, newss.getTotalElements(), size);
				result.setPages(pages);
				result.setData(newss.getContent());
				result.setSuccess("查询成功！");
			}else {
				result.setError("暂时无此分类的新闻信息！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setError("发生异常错误！");
		}
		return result;
	}
	/**
	 * 查询热门新闻
	 * @return
	 */
	@RequestMapping(value = "findHotNews", method = RequestMethod.GET)
	public Result<News> findHotNews(
			@RequestParam(value = "page",defaultValue = "0") Integer page,
			@RequestParam(value = "size", defaultValue = "10") Integer size){
		logger.info("\n 查询热门新闻（findHotNews）开始：page = " + page + "\t size = "+ size);
		Result<News> result = new Result<>();
		try {
			Order order 	= new Order(Direction.DESC, "count"); // 根据字段count进行降序排序
			PageRequest pageRequest = PageRequest.of(page, size, new Sort(order));// 分页排序查询
			Page<News> news = newsService.listNews(pageRequest);
			
			if(news != null && news.getContent() != null && news.getContent().size() > 0) {
				Pages pages = new Pages(page, news.getTotalElements(), size);
				
				result.setPages(pages);
				result.setData(news.getContent());
				result.setSuccess("查询成功！");
			}else {
				result.setError("暂无新闻！请稍后再试");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setError("发生异常错误！");
			
		}
		logger.info("\n 查询热门新闻（findHotNews）结束：result = " + result);
		return result;
	}
}
